package com.bourse.core.services.cotation;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.bourse.core.exceptions.TimeSerieException;
import com.bourse.core.ibatis.CotationDao;
import com.bourse.core.utils.Cotation;
import com.bourse.core.utils.IsinCode;
import com.bourse.core.utils.TimeSerieObject;
import com.googlecode.ehcache.annotations.Cacheable;

public class CotationDataServiceImpl implements CotationDataService{
	
	private Logger LOGGER = Logger.getLogger(CotationDataServiceImpl.class);
	
	private CotationDao cotationDao;

	/**
	 * see@CotationDataService#getCotation
	 */
	@Cacheable(cacheName = "cotationMap") 
	public Map<IsinCode,TimeSerieObject<Cotation>> getCotations(){

		Map<IsinCode, TimeSerieObject<Cotation>> cotationMap = new HashMap<IsinCode, TimeSerieObject<Cotation>>();
		List<Cotation> cotations = cotationDao.getCotations();
		
		LOGGER.info("[Cotation Loader] - Build cotation map.");
		for(Cotation cotation : cotations){
			IsinCode isin = cotation.getIsin();
			TimeSerieObject<Cotation> tso = cotationMap.get(isin);
			if(tso==null){
				tso = new TimeSerieObject<Cotation>();
				cotationMap.put(isin, tso);
			}
			
			try{
				tso.add(cotation.getDate(), cotation);
			}catch(TimeSerieException tsoException){
				LOGGER.error("[Cotation Loader] - Error while building cotationMap "+tsoException.getMessage());
			}
		}		
		return cotationMap;
	}
	

	public void insertCotation(List<Cotation> cotations) {
		cotationDao.insertCotation(cotations);
	} 
	
	
	
	public void setCotationDao(CotationDao cotationDao) {
		this.cotationDao = cotationDao;
	}

}
